export function parser(file, tokens) {
  let token = null;
  const next = () => {
    token = tokens.next().value;
    console.log("parser: ", token && token.type);
  };

  const NumbericLiteral = () => {
    if (token.type === "NumbericLiteral") {
      const _token = token;
      next();
      return _token;
    }
  };

  const PlusToken = () => {
    if (token.type === "PlusToken") {
      const _token = token;
      next();
      return _token;
    }
  };

  const BinaryExpressionTail = (left) => {
    const plus = PlusToken();
    if (!plus) return left;
    const right = NumbericLiteral();
    if (!right) {
      console.log(token);
      throw new SyntaxError(
        `Expected token type "NumbericLiteral" got "${token.type}" at ${file}:${token.loc.start.line}:${token.loc.start.column}`
      );
    }

    const node = {
      type: "BinaryExpression",
      left,
      operatorToken: plus,
      right,
      // TODO: loc
    };

    return BinaryExpressionTail(node);
  };

  const BinaryExpression = () => {
    const head = NumbericLiteral();
    if (!head) return null;

    return BinaryExpressionTail(head);
  };

  next();
  const program = BinaryExpression();

  if (token.type !== "EndOfFileToken") {
    throw new SyntaxError(
      `Expected token type "EndOfFileToken" got "${token.type}" at ${file}:${token.loc.start.line}:${token.loc.start.column}`
    );
  }

  return program;

  // const result = [];
  // let last = null;
  // let left = null;
  // let plusToken = null;
  // for (const token of tokens) {
  //   if (plusToken) {
  //     const right = token;
  //     result.push({
  //       type: "BinaryExpression",
  //       left,
  //       right,
  //     });
  //   }

  //   if (token.type === "PlusToken") {
  //     left = last;
  //     plusToken = token;
  //   }

  //   last = token;
  // }

  // return result;
}
